const fs = require('fs');
const path = require('path');

/**
 * @description 没有目录创建目录
 * @param directoryPath 目录路径
 */ 
function haveDirectoryPath(directoryPath) {
	return new Promise((reslove, reject) => {
		fs.exists(directoryPath, (exists) => {
			if (!exists) {
				fs.mkdir(directoryPath, {
					recursive: true
				}, (err) => {
					if (err) throw err;
					reslove()
				});
			} else {
				reslove()
			}
		});
	})
}

/**
 * @description 读取文件
 * @param filePath 目录路径
 */ 
function readFile(filePath) {
	return new Promise((resolve, reject) => {
		fs.readFile(filePath, 'utf8', (err, data) => {
			if (err) {
				resolve({})
			} else {
				resolve(JSON.parse(data));
			}
		});
	});
}

/**
 * @description 读取文件
 * @param data  内容
 * @param filePath 目录路径
 * @return Promiece 数据内容变化
 */ 
async function writeFileReturnData(data = {}, filePath = path.resolve(__dirname, "localCache/store/index.json")) {
	let res = await readFile(filePath)
	data = {
		...res,
		...data
	};
	if (typeof data != "string") {
		data = JSON.stringify(data)
	}
	await haveDirectoryPath(path.resolve(__dirname, "localCache/store"));
	return new Promise((resolve, reject) => {
		fs.writeFile(filePath, data, 'utf8', (err) => {
			if (err) {
				reject(err);
			} else {
				resolve(data);
			}
		});
	});
}
writeFileReturnData().then(res=>{
	console.log("查看内容",res)
})
console.log()
